import 'package:english_words/english_words.dart';
import 'package:flutter/material.dart';

class ListLongDemo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _ListLongState();
}

class _ListLongState extends State<ListLongDemo> {
  static const loadingTag = '##loading##';
  var _words = <String>[loadingTag];
  ScrollController _controller = ScrollController();
  bool showTopBtn = false;

  @override
  void initState() {
    super.initState();
    _controller.addListener(() {
      print(_controller.offset);
      if (_controller.offset < 1000 && showTopBtn) {
        setState(() {
          showTopBtn = false;
        });
      } else if (_controller.offset >= 1000 && !showTopBtn) {
        setState(() {
          showTopBtn = true;
        });
      }
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          title: Text('长列表控件及控制'),
          centerTitle: true,
        ),
        body: ListView.separated(
          physics: BouncingScrollPhysics(),
          controller: _controller,
          itemCount: _words.length,
          itemBuilder: (context, index) {
            if (_words[index] == loadingTag) {
              if (_words.length - 1 < 100) {
                _retrieveData();
                return Container(
                  padding: EdgeInsets.all(16),
                  alignment: Alignment.center,
                  child: SizedBox(
                    width: 24,
                    height: 24,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                    ),
                  ),
                );
              } else {
                return Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.all(16),
                  child: Text('我是有底线的', style: TextStyle(color: Colors.grey)),
                );
              }
            }
            return ListTile(
              leading: Icon(Icons.phone),
              title: Text(_words[index]),
            );
          },
          separatorBuilder: (context, index) => Divider(
            height: 0.5,
            indent: 15,
            endIndent: 15,
          ),
        ),
        floatingActionButton: !showTopBtn
            ? null
            : FloatingActionButton(
                child: Icon(Icons.arrow_upward),
                onPressed: () {
                  _controller.animateTo(0,
                      duration: Duration(microseconds: 200),
                      curve: Curves.ease);
                },
              ),
      );

  void _retrieveData() {
    Future.delayed(Duration(seconds: 3)).then((value) {
      // 重新构建列表
      setState(() {
        _words.insertAll(_words.length - 1,
            generateWordPairs().take(20).map((e) => e.asPascalCase).toList());
      });
    });
  }
}
